package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.event.model.DriverPowerOfflineEvent;
import com.ybkj.daijia.server.event.model.MemberNoticeEvent;
import com.ybkj.daijia.server.event.model.OrderFinishEvent;
import com.ybkj.daijia.server.mapper.MemberNoticeMapper;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.MemberNotice;
import com.ybkj.daijia.server.model.NoticeXPassenger;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.NoticeXPassengerService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class OrderFinishEventListener implements ApplicationListener<OrderFinishEvent> {

    private static final Logger logger = LoggerFactory.getLogger(OrderFinishEventListener.class);

    @Autowired
    private SmsService smsService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberNoticeMapper memberNoticeMapper;

    @Autowired
    private NoticeXPassengerService noticeXPassengerService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    @Async
    public void onApplicationEvent(OrderFinishEvent event) {

        logger.debug("order finish event:{}", "");

        ReactorVo vo = (ReactorVo) event.getSource();

        Order order = vo.getOrder();
        order = orderService.findOne(order.getId());

        Driver driver = driverService.findOne(order.getDriverId());

        //web推送
//		int applyWorkCar = -1;
//		List<WorkCarPickup> wcps=workCarPickupService.listOldWjAndJsAndSc(order.getDriverId());
//		if(!CollectionUtils.isEmpty(wcps)){
//			if(wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_WEIJIE || wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_YIJIE){
//				applyWorkCar = WorkCarPickup.WORKCAR_WEIJIE;
//			}
//			else if(wcps.get(0).getStatus()==WorkCarPickup.WORKCAR_SHANGCHE){
//				applyWorkCar = WorkCarPickup.WORKCAR_YIJIE;
//			}
//		}
//		
//		int busyStatus = -1;
//		if(null!=order.getDaokehuTime()){
//			if(null==order.getDaijiaTime2()){
//				busyStatus = 0;
//			}
//			else{
//				busyStatus = 1;
//			}
//		}

        JSONObject jsonObject = new JSONObject();
        jsonObject
            .put("message", "服务人员" + driver.getRealname() + " 已完成工单：" + order.getOrderNumber());
        jsonObject.put("lng", driver.getLongitude());
        jsonObject.put("lat", driver.getLatitude());
        jsonObject.put("driverID", driver.getId());
        jsonObject.put("orderID", order.getId());
//		jsonObject.put("applyWorkCar", applyWorkCar);
//		jsonObject.put("busyStatus", busyStatus);

        jsonObject.put("isworkCar", driver.isWorkCar());
        Company mainCompany = companyService.getMain();
        Company orderCompany = companyService.findOne(order.getCompanyId());
        //地区推送
        jsonObject.put("type", "finish_area");
        WebSocketSend.boardcastToArea(jsonObject, orderCompany.getCityName(), mainCompany.getId());
        //对应公司推送
        jsonObject.put("type", "finish_company");
        WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());

        //发送短信
        String payway = order.getPreAndAfterPayType();

        Passenger passenger = memberService.findOnePassenger(order.getClientId());

        Company memberCompany = companyService.findOne(passenger.getCompanyId());
        Company driverCompany = companyService.findOne(driver.getCompanyId());

        Setting setting = settingUtils.get();
        if (setting.isSmsMainCompany()) {
            orderCompany = mainCompany;
        }
//        if (setting.getWhichServicePhone() == 1) {
//            maincompany = companyService.findOne(order.getCompanyId());
//        }

        String content = "";
        try {
            SmsTemplet templet = smsService
                .findByAlias(orderCompany.getId(), SmsType.orderFinished);
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
//        		content=templet.getContent().replaceAll("\\{订单号\\}", "***" + order.getOrderNumber().substring(8)).replaceAll("\\{服务人员工号\\}", driver.getUsername()).replaceAll("\\{等候时间\\}", order.getWaitedTime()+ "").replaceAll("\\{行驶公里\\}", order.getMileage() + "").replaceAll("\\{收费金额\\}", order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString()).replaceAll("\\{支付方式\\}", payway).replaceAll("\\{投诉建议电话\\}", orderCompany.getTelephone());
//        		smsService.sendSms(order.getClientPhone(), "orderFinished", "{\"订单号\":\"" + "***" + order.getOrderNumber().substring(8) + "\",\"服务人员工号\":\"" + driver.getUsername() + "\",\"等候时间\":\"" + order.getWaitedTime() + "" + "\",\"行驶公里\":\"" + order.getMileage() + "" + "\",\"收费金额\":\"" + order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\",\"支付方式\":\"" + payway + "\",\"投诉建议电话\":\"" + orderCompany.getTelephone() + "\"}", orderCompany.getId(), 0, orderCompany.getSignName());
                //发送短信（改）
                com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                smsParam.put("order", order.getOrderNumber().substring(8));
                smsParam.put("driver", driver.getUsername());
                smsParam.put("waitTime", order.getWaitedTime());
                smsParam.put("mileage", order.getMileage());
                smsParam.put("realCash",
                    order.getRealCash().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                smsParam.put("payWay", payway);
                smsParam.put("tel", orderCompany.getTelephone());
                smsService.sendSms(order.getClientPhone(), templet.getTemplateId(),
                    smsParam.toJSONString(), orderCompany.getId(), 0, orderCompany.getSignName());
            }
        } catch (Exception e) {
            logger.error("发送短信发生异常：{}", e.getMessage());
        }

        if (StringUtils.isNotBlank(content)) {
            //自动发送客户通知
            MemberNotice memberNotice = new MemberNotice();
            memberNotice.setCompanyId(memberCompany.getId());
            memberNotice.setOperating("系统");
            memberNotice.setPassengerIds("," + passenger.getId() + ",");
            memberNotice.setContent(content);
            memberNoticeMapper.insertRecord(memberNotice);

            NoticeXPassenger noticeXPassenger = new NoticeXPassenger();
            noticeXPassenger.setPassengerId(passenger.getId());
            noticeXPassenger.setNoticeId(memberNotice.getId());
            noticeXPassenger.setHasRead(false);
            noticeXPassengerService.save(noticeXPassenger);

            List<Passenger> passengers = new ArrayList<Passenger>();
            passengers.add(passenger);

            MemberNoticeEvent memberNoticeEvent = new MemberNoticeEvent(memberNotice, passengers);
            applicationEventMulticaster.multicastEvent(memberNoticeEvent);
        }

        //服务人员最低上班余额
        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)
            && driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
            && driverCompany.getLowestWorkVirtual().doubleValue() != 0
            && driver.getVirtual().doubleValue() < driverCompany.getLowestWorkVirtual()
            .doubleValue()) {

            driver.setStatus(Driver.DRIVER_OFFLINE);
            driverService.updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

            DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(driver,
                Driver.DRIVER_ONLINE, "sys");
            applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);

        } else {
//			try {
//				List<Order> yupaidanlist=orderService.listByDriverAndStatus(driver.getId(), Order.ORDER_STATUS_YUPAIDAN);
//				if(!CollectionUtils.isEmpty(yupaidanlist)){
//					
//					Collections.sort(yupaidanlist, new Comparator<Order>() {
//				        public int compare(Order arg0, Order arg1) {
//				            return arg0.getServerTime().compareTo(arg1.getServerTime());
//				        }
//				    });
//					
//					Order yupaiOrder=yupaidanlist.get(0);
//					Driver yupaiDriver=driverService.findOne(driver.getId());
//					if(null!=yupaiDriver && yupaiDriver.getStatus().equals(Driver.DRIVER_ONLINE)){
//						orderService.yupaidan(yupaiDriver, yupaiOrder, "auto");
//						
//						//派单事件
//						OrderPaidanEvent paidanEvent = new OrderPaidanEvent(order);
//						applicationEventMulticaster.multicastEvent(paidanEvent);
//					}
//				}
//			} catch (Exception e1) {
//				logger.debug(e1.getMessage());
//			}
        }


    }

}
